<!--
 * @Author: 胡海
 * @Date: 2020-11-22 16:12:24
 * @LastEditors: 胡海
 * @LastEditTime: 2020-11-22 16:13:52
 * @Description: 
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Object.defineProperty</title>
    <script src="../vue/src/vue.js"></script>
</head>
<body>
    	
		<div id="app">
			<button id="btn">改变数据</button>
			<h2 id="title">这是标题</h2>
		</div>

		<script>
			var data = {
				title: '新闻',
				miaov:1
			}

			// 数据劫持，转成getter和setter

			observer(data)
			

			function observer(obj){
				Object.keys(obj).forEach((item) => {
					defineReactive(obj,item,obj[item])
				})	
			}

			function defineReactive(obj,key,value){
				Object.defineProperty(obj,key, {
					get(){
						return value;
					},
					set(newValue){
						value = newValue;
						title.innerHTML = newValue ;
					}
				})	
			}

			console.log(data);
			

			var title = document.getElementById('title');
			var btn = document.getElementById('btn');

			title.innerHTML = data.title;




			btn.onclick = function (){
				data.title = '数据变了';
			}



		</script>
</body>
</html>